package com.twu.biblioteca;

import javax.security.auth.login.FailedLoginException;

/**
 * Created with IntelliJ IDEA.
 * User: dbelsey
 * Date: 29/01/13
 * Time: 17:34
 */
public class BibliotecaAppData {
    LibraryInventory libraryInventory;
    UserList userList;
    boolean applicationRunning;
    String loggedInUsername;

    public BibliotecaAppData(LibraryInventory libraryInventory, UserList userList){
        this.libraryInventory = libraryInventory;
        this.userList = userList;
        applicationRunning = true;
        loggedInUsername = "";
    }

    public BibliotecaAppData(){
        this.libraryInventory = new LibraryInventory();
        this.userList = new UserList();
    }

    public LibraryInventory getLibraryInventory(){
        return libraryInventory;
    }

    public UserList getUserList(){
        return userList;
    }

    public void stop(){
        applicationRunning = false;
    }

    public boolean isRunning(){
        return applicationRunning;
    }

    public boolean isUserLoggedIn() {
        return !(loggedInUsername.equals(""));
    }

    public boolean logInUser(String usernameToLogIn, String password) throws FailedLoginException{
        // TODO: checking for already logged in user when logging in. for now, just logs out previous user on attempt
        logout();
        if(userList.doesUserExist(usernameToLogIn)){
            if(userList.checkPassword(usernameToLogIn, password)){
                    // login successful
                loggedInUsername = usernameToLogIn;
                return true;
            }
            else throw new FailedLoginException("Login failed: Incorrect password");
        }
        else throw new FailedLoginException("Login failed: Username not recognised. Please contact a Librarian");
    }

    public void logout(){
        loggedInUsername = "";
    }

    public String getLoggedInUsername(){
        return loggedInUsername;
    }

    public String getLoggedInUserFullName(){
        return getLoggedInUserData().getName();
    }

    public UserData getLoggedInUserData(){
        return userList.getUserData(loggedInUsername);
    }
}
